package controller

import (
	"fmt"
	"gin/common"
	"gin/model"
	"gin/response"
	"gin/util"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"log"
	"net/http"
	url2 "net/url"
	"sort"
	"strconv"
	"strings"
	"time"
)

func WxLogin(ctx *gin.Context) {
	code := ctx.Query("code")
	if len(code) > 0 {
		result := common.CodeChangeAccessToken(code)
		if _, ok := result["errcode"]; ok {
			response.Success(ctx, gin.H{"errcode": result["errcode"], "errmsg": result["errmsg"]}, "success")
			return
		}
		DB := common.GetDB()
		user := model.OpenidGetUser(common.GetDB(), result["openid"])
		if user.Uid > 0 {
			token, _ := common.ReleaseToken(user.Uid)
			user1, token1 := getReturnInfo(user, token)
			response.Success(ctx, gin.H{"user": user1, "token": token1}, "success")
			return
		}
		info := common.OpenidGetUserinfo(result)
		fmt.Println("info=", info)
		if len(info.Openid) == 0 {
			response.Fail(ctx, gin.H{}, "获取用户信息失败")
			return
		}
		var create = model.UserInfo{
			Openid:        info.Openid,
			Nick:          info.Nick,
			AvatarUrl:     info.AvatarUrl,
			Country:       info.Country,
			City:          info.City,
			Province:      info.Province,
			Gender:        info.Gender,
			LastLoginIp:   util.GetLocalIP(),
			LastLoginTime: util.DateFormat(0),
			LoginTimes:    1,
			CreateTime:    util.DateFormat(0),
			UpdateTime:    util.DateFormat(0),
		}
		DB.Table("cat_meal_user").Create(create)
		user = model.OpenidGetUser(common.GetDB(), create.Openid)
		if user.Uid > 0 {
			token, _ := common.ReleaseToken(user.Uid)
			user1, token1 := getReturnInfo(user, token)
			response.Success(ctx, gin.H{"user": user1, "token": token1}, "success")
			return
		}
		response.Fail(ctx, gin.H{}, "登录失败")
	} else {
		url := common.GetAuthorizeUrl()
		ctx.Redirect(http.StatusFound, url)
	}
}

type SignPackage struct {
	AppId     string
	NonceStr  string
	Timestamp string
	Signature string
	Url       string
}

func GetSignPackage(ctx *gin.Context) {
	timestamp := strconv.FormatInt(int64(time.Now().Unix()), 10)
	fmt.Println(timestamp)
	code, ticket := common.GetTicket()
	if code != 0 {
		fmt.Println("code=", code)
		response.Fail(ctx, gin.H{}, "微信权限不够")
		return
	}
	nonceStr := util.RandomString(16)
	url, _ := url2.QueryUnescape(ctx.Query("url"))
	jsapiTicket := "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url
	signPackage := SignPackage{
		AppId:     viper.GetString("wx.appid"),
		NonceStr:  nonceStr,
		Timestamp: timestamp,
		Signature: util.SHA1(jsapiTicket),
		Url:       url,
	}
	response.Success(ctx, gin.H{"package": signPackage}, "success")
	return
}

func WxService(ctx *gin.Context) {
	echostr := ctx.Query("echostr")
	signature := ctx.Query("signature")
	timestamp := ctx.Query("timestamp")
	token := "ad"
	nonce := ctx.Query("nonce")
	if len(echostr) > 0 { //第一次绑定
		stringList := []string{timestamp, token, nonce}
		sort.Strings(stringList)
		fmt.Println(stringList, signature)
		newStr := strings.Join(stringList, "")
		sign := util.SHA1(newStr)
		fmt.Println(sign)
		if sign != signature {
			response.Fail(ctx, gin.H{}, "签名失败")
		} else {
			ctx.String(200, echostr)
		}
	}
	textMsg2 := make(map[string]interface{})
	err := ctx.BindJSON(&textMsg2)
	fmt.Println(textMsg2)
	textMsg1 := make(map[string]interface{})
	err2 := ctx.ShouldBindXML(&textMsg1)
	fmt.Println(textMsg1, err2)
	var textMsg common.WXTextMsg
	err = ctx.ShouldBindXML(&textMsg)
	if err != nil {
		log.Printf("[消息接收] - XML数据包解析失败: %v\n", err)
		return
	}
	sprintf := fmt.Sprintf("[消息接收] - 收到消息, 消息类型为: %s, 消息内容为: %s\n", textMsg.MsgType, textMsg.Content)
	fmt.Println(sprintf)
	if textMsg.MsgType == "text" {
		xml := `<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[%s]]></MsgType>
		<Content><![CDATA[%s]]></Content>
		</xml>`
		sprintf := fmt.Sprintf(xml, "o57jF6IcLVgzG5r8iG0DpPzqanKM", "o57jF6IcLVgzG5r8iG0DpPzqanKM", "2", "text", "test")
		util.LogInfo(sprintf)
		ctx.String(200, sprintf)
	}
}
